package com.shadt.pay.wechat.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shadt.core.util.ConfigUtil;
import com.shadt.core.util.HttpsServiceRequest;
import com.shadt.core.util.IServiceRequest;
import com.shadt.core.util.RandomStringGenerator;
import com.shadt.core.util.Signature;
import com.shadt.pay.dao.ShadtOrderDao;
import com.shadt.pay.entity.Pay_Shadt_Order;
import com.shadt.pay.model.PayNotifyReturn;
import com.shadt.pay.wechat.dao.WeChatNotityDao;
import com.shadt.pay.wechat.dao.WeChatOrderDao;
import com.shadt.pay.wechat.dao.WeChatPreOrderDao;
import com.shadt.pay.wechat.entity.Pay_WeChat_Notity;
import com.shadt.pay.wechat.entity.Pay_WeChat_Order;
import com.shadt.pay.wechat.entity.Pay_WeChat_Preorder;
import com.shadt.pay.wechat.model.WeChatOrderQueryReceive;
import com.shadt.pay.wechat.model.WeChatOrderReceive;
import com.shadt.pay.wechat.model.WeChatOrderReturn;
import com.shadt.pay.wechat.service.WeChatPayService;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

/**
 * 微信支付业务层实现类
 * 
 * @author SongR
 * 
 */
@Service
public class WeChatPayServiceImpl implements WeChatPayService {
	@Autowired
	WeChatPreOrderDao wcpoDao;
	@Autowired
	WeChatNotityDao notityDao;
	
	@Autowired
	WeChatOrderDao weChatOrderDao;
	@Autowired
	ShadtOrderDao orderDao;

	/**
	 * 微信统一支付请求
	 */
	public Pay_Shadt_Order unifiedOrder(String orderId, String ip)
			throws Exception {
		WeChatOrderReceive or = new WeChatOrderReceive();// 传输订单数据
		Pay_Shadt_Order order = orderDao.get(Pay_Shadt_Order.class, Integer.parseInt(orderId));
		if (order != null) {
			or.setAppid(order.getShadtApp().getWeChatApp().getWechat_app_id());
			or.setBody(order.getOrder_body());
			or.setMch_id(order.getShadtApp().getWeChatApp().getWechat_mch_id());
			or.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			or.setNotify_url(ConfigUtil.get("wechatconfig", "notityurl"));
			or.setSpbill_create_ip(ip);
			or.setTotal_fee(order.getOrder_totalfee().toString());
			or.setOut_trade_no(order.getOrder_tradeno());
			or.setTrade_type("APP");
			or.setSign(Signature.getSign(or, order.getShadtApp().getWeChatApp().getWechat_app_key()));
			XStream xss = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));// 解决XStream对出现双下划线的bug
			String postDataXML = xss.toXML(or);
			System.out.println("发送给微信统一下单的数据是：\n"+postDataXML);
			IServiceRequest is = new HttpsServiceRequest();
			String wus = is.sendPost(ConfigUtil.get("wechatconfig", "unifiedorderurl"), or);
			System.out.println("微信统一下单返回数据：\n"+wus);
			XStream xs = new XStream();
			xs.alias("xml", WeChatOrderReturn.class);
			WeChatOrderReturn wor = (WeChatOrderReturn) xs.fromXML(wus);
			Pay_WeChat_Preorder wcor = new Pay_WeChat_Preorder();
			wcor.setAppid(order.getShadtApp().getWeChatApp().getWechat_app_id());
			wcor.setPartnerid(order.getShadtApp().getWeChatApp().getWechat_mch_id());
			wcor.setPrepayid(wor.getPrepay_id());
			wcor.setOrderId(order.getOrder_id()+"");
			wcor.setWechat_package("Sign=WXPay");
			wcor.setNoncestr(RandomStringGenerator.getRandomStringByLength(32));
			wcor.setTimestamp((System.currentTimeMillis() / 1000) + "");
			wcor.setAppkey(order.getShadtApp().getWeChatApp().getWechat_app_key());
			wcor.setCreatDate(new Date());
			wcor.setRedirect_uri(order.getRedirect_uri());
			wcpoDao.saveOrUpdate(wcor);
			order.setOrder_trade_status(1);
			order.setOrder_trade_type("WECHAT");
			orderDao.saveOrUpdate(order);
		}
		return order;
	}

	/**
	 * 获取sdk支付需要的参数
	 */
	public Pay_WeChat_Preorder getPayInfo(String orderId) throws Exception {
		Pay_WeChat_Preorder pwp = wcpoDao.get("from Pay_WeChat_Preorder where orderId='" + orderId + "'");
		return pwp;
	}

	/**
	 * 微信通知
	 */
	public void notity(String reqXml) throws Exception {
		XStream xs = new XStream();
		xs.alias("xml", Pay_WeChat_Notity.class);
		Pay_WeChat_Notity wn = (Pay_WeChat_Notity) xs.fromXML(reqXml);
		wn.setWeChat_notity_id(UUID.randomUUID().toString());
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("order_tradeno", wn.getOut_trade_no());
		Pay_Shadt_Order order = orderDao.get("from Pay_Shadt_Order where order_tradeno=:order_tradeno",params);
		order.setOrder_trade_type("WECHAT");
		order.setOrder_trade_time(new Date());
		if (wn.getReturn_code().equals("SUCCESS")) {
			order.setOrder_trade_status(9);
		} else {
			order.setOrder_trade_status(2);
		}
		orderDao.saveOrUpdate(order);
		PayNotifyReturn notify = new PayNotifyReturn();
		notify.setAppid(order.getShadtApp().getShadt_app_id());
		notify.setMch_id(order.getShadtApp().getShadt_mch_id());
		notify.setNonce_str(wn.getNonce_str());
		notify.setReturn_code("SUCCESS");
		notify.setResult_code("SUCCESS");
		notify.setTrade_type("WECHAT");
		notify.setTotal_fee(wn.getTotal_fee()+"");
		notify.setOut_trade_no(wn.getOut_trade_no());
		notify.setTime_end(wn.getTime_end());
		notify.setSign(Signature.getSign(notify, order.getShadtApp().getShadt_app_key()));
		IServiceRequest is = new HttpsServiceRequest();
		@SuppressWarnings("unused")
		String s = is.sendPost(order.getOrder_notifyUrl(), notify,PayNotifyReturn.class);
		notityDao.save(wn);
	}

	/**
	 * 实现微信支付结果查询
	 */
	public String orderQuery(String reqXml) throws Exception {
		XStream xs = new XStream();
		xs.alias("xml", WeChatOrderQueryReceive.class);
		WeChatOrderQueryReceive orderQuery = (WeChatOrderQueryReceive) xs.fromXML(reqXml);
		IServiceRequest is = new HttpsServiceRequest();
		String respXml = is.sendPost(ConfigUtil.get("wechatconfig", "orderqueryurl"), orderQuery);
		XStream xss = new XStream();
		xss.alias("xml", Pay_WeChat_Order.class);
		Pay_WeChat_Order wechatOrder = (Pay_WeChat_Order) xs.fromXML(respXml);
		if(wechatOrder.getReturn_code().equals("SUCCESS")){
			
		}
		return null;
	}

}
